<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/7/25
 * Time: 15:41
 */

namespace app\api\model;

use think\Model;
use think\Request;
use app\api\controller\GoogleMap;

class HotelSpu extends Model
{
    public function getAdminHotelList($where=[],$offset=0,$field="hotel_id,name")
    {
        $where['is_deleted'] = 0;
        if(empty($offset)){
            return $this->field($field)->where($where)->select();
        }else{
            return $this->where($where)->paginate($offset);
        }

    }

    //获取星级参数
    function getHotelLevels()
    {
        return [
            '1'=>'1星级',
            '2'=>'2星级',
            '3'=>'3星级',
            '4'=>'4星级',
            '5'=>'5星级',
        ];
    }

    public function createHotel($data)
    {
        //检查数据是否缺失
        $required_field = ['city_id','name','introduce','lat','lng','level','thumb'];
        foreach ($required_field as $field){
            if(empty($required_field)){
                return '缺少参数'.$field;
            }
        }
        //检查名称是否重复
        if($this->checkExistHotelName($data['name'])){return '存在同名的酒店名称';}
        //补充城市信息
        $res = $this->fillCityData($data);
        if($res){
            return $res;
        }
        //存在重复 返回数据
        $insertData = [
            'city_id'=>$data['city_id'],
            'city_name'=>$data['city_name'],
            'remark'=>$data['remark']??'',
            'currency'=>$data['currency']??'',
            'name'=>$data['name'],
            'en_name'=>$data['eng_name']??'',
            'address'=>$data['address']??'',
            'eng_introduce'=>$data['eng_introduce']??'',
            'introduce'=>$data['introduce'],
            'lat'=>$data['lat'],
            'lng'=>$data['lng'],
            'level'=>$data['level'],
            'service_fee'=>$data['service_fee']??'',
            'breakfast_fee'=>$data['breakfast_fee']??'',
            'charging_fee'=>$data['charging_fee']??'',
            'thumb'=>$data['thumb'],
            'source_id'=>$data['source_id']??0,
            'channel'=>$data['channel']??'',
            'create_time'=>time(),
            'update_time'=>time(),
        ];
        //数据缺失直接返回错误
        if(!empty($data['createPOI']) && $data['createPOI']=='on'){
            //插入POI
            $exist_POI = db('poi')->where(['name'=>$data['name']])->find();
            if(empty($exist_POI)){
                $poiModel = new Poi();
                $insertData['groupid'] = $insertData['city_id'];
                $insertData['typeid'] = 5;
                $insertData['eng_name'] = $insertData['en_name'];
                $poiModel->allowField(true)->save($insertData);
                $poiId = db()->getLastInsID();
                $insertData['poi_id'] = $poiId;
            }else{
                $insertData['poi_id'] = $exist_POI['id'];
            }
        }
        $this->allowField(true)->save($insertData);
    }

    public function updateHotel($data)
    {
        //检查数据是否缺失
        $required_field = ['id','city_id','name','introduce','lat','lng','level','thumb'];
        foreach ($required_field as $field){
            if(empty($required_field)){
                return '缺少参数'.$field;
            }
        }
        //检查名称是否重复
        if($this->checkExistHotelName($data['name'],$data['id'])){return '存在同名的酒店名称';}
        //补充城市信息
        $res = $this->fillCityData($data);
        if($res){
            return $res;
        }
        $insertData = [
            'city_id'=>$data['city_id'],
            'city_name'=>$data['city_name'],
            'remark'=>$data['remark']??'',
            'currency'=>$data['currency']??'',
            'name'=>$data['name'],
            'en_name'=>$data['eng_name']??'',
            'address'=>$data['address']??'',
            'eng_introduce'=>$data['eng_introduce']??'',
            'introduce'=>$data['introduce'],
            'lat'=>$data['lat'],
            'lng'=>$data['lng'],
            'level'=>$data['level'],
            'service_fee'=>$data['service_fee']??'',
            'breakfast_fee'=>$data['breakfast_fee']??'',
            'charging_fee'=>$data['charging_fee']??'',
            'thumb'=>$data['thumb'],
            'source_id'=>$data['source_id'],
            'channel'=>$data['channel'],
            'update_time'=>time(),
        ];
        $this->allowField(true)->save($insertData,['hotel_id'=>$data['id']]);
    }
    //补全城市信息
    public function fillCityData(&$data)
    {
        $city = db('city c')
            ->join('city p','p.id=c.groupid','left')->field('c.id,c.name,p.currency_code')
            ->where('c.id',$data['city_id'])->find();
        if(!empty($city)){
            $data['currency'] = $city['currency_code'];
            $data['city_name'] = $city['name'];
        }else{
            return '缺少城市信息';
        }
    }

    //检查是否存在相同的酒店名称
    public function checkExistHotelName($name,$id=0)
    {
        $where['name'] = $name;
        if(!empty($id)){$where['hotel_id'] = ['neq',$id];}
        return $this->where($where)->find();
    }
    //定制库启用的所有城市列表
    public function getCityList($where=[])
    {
        $where['status'] = 1;
        $where['type'] = 'CITY';
        $city = db("city")
            ->where($where)
            ->field("id,concat(name,'(',eng_name,')') as name")
            //->limit(20)
            ->select();
        return $city;
    }

    public function getHotelDetail($id)
    {
        $where['hotel_id'] = $id;
        $details = $this->where($where)->find();
        if(!empty($details['channel']) && !empty($details['source_id'])){
            $details['thirdData'] = $this->getThirdHotelDetails($details['channel'],$details['source_id']);
        }else{
            $details['thirdData'] = new \ArrayObject();
        }
        return $details;
    }

    public function delHotel($id){
        $where['hotel_id'] = $id;
        return $this->where($where)->update([
            'is_deleted'=>1,
            'delete_time'=>time()
        ]);
    }

    //按照入住时间和类型检索酒店
    public function searchRoomSku($data)
    {
        //入住时间
        $checkInDate = $data['checkInDate'];
        //离开时间
        $checkOutDate = $data['checkOutDate'];
        //酒店ID
        $hotelId = $data['hotelId'];
        //符合属性值
        $attrValues = $data['attrValues'];
        //返回的均为单间房价
        $hotelInfo = db('hotel_spu')->find($hotelId);
        if(empty($hotelInfo)) return '酒店信息不存在';
        $exchange_rate = 1;
        if(!empty($hotelInfo['currency'])){
            $exchange_rate = db('exchange')->where('currency_code',$hotelInfo['currency'])->find()['exchange_rate']??1;
        }
        //检索支持条件的房间SKU

        $roomIds = db('hotel_room_sku')->where(['hotel_id'=>$hotelId,'is_delete'=>0])->column('id');
        if(empty($roomIds)) return '暂未设置售卖房型';
        if(!empty($data['attrValues'])){
            $roomSku = db('hotel_room_attr_value')
                ->field('count(*) as count,room_id')
                ->where(['attr_value_id'=>['in',$attrValues],'room_id'=>['in',$roomIds]])
                ->having('count >= '.count($attrValues))
                ->group('room_id')
                ->select();
            if(empty($roomSku)) return '未匹配到符合条件房型';
            $roomSkuIds = array_column($roomSku,'room_id');
        }else{
            $roomSkuIds = $roomIds;
        }


        //检索酒店是否设置价格
        $hotelPriceList = db('hotel_room_sku_price')->field("id,room_id,stay_day,sales_price,market_price")->where([
            'hotel_id'=>$hotelId,
            'stay_day'=>[['egt',$checkInDate],['lt',$checkOutDate]],
            'room_id'=>['in',$roomSkuIds],
            'stock'=>['gt',0],
            'is_delete'=>0
        ])->select();
        if(empty($hotelPriceList)){
            return '暂无房间可售！';
        }
        $hotelRoomSkuPriceList = [];
        $hotelRoomSkuIds = array_unique(array_column($hotelPriceList,'room_id'));
        $hotelRoomSkuInfos = db('hotel_room_sku')->field('id,name,en_name')->where(['id'=>['in',$hotelRoomSkuIds]])->select();
        //按房间归类
        foreach ($hotelRoomSkuInfos as $key=>$value){
            $roomAttrValues = db('hotel_room_attr_value rv')
                ->join('hotel_spu_attr_value hv','hv.id=rv.attr_value_id','left')
                ->field('hv.attr_value as name,rv.attr_value_id as id')
                ->where('rv.room_id',$value['id'])
                ->select();
            $hotelRoomSkuPriceList[] = [
                'roomId'=>$value['id'],
                'roomName'=>$value['name'],
                'roomEnName'=>$value['en_name'],
                'exchange_rate'=>$exchange_rate,
                'attrs'=>!empty($roomAttrValues)?$roomAttrValues:[],
                'priceList'=>[]
            ];
        }

        //检索出所有的属性值
        foreach ($hotelRoomSkuPriceList as $k=>$v) {
            foreach ($hotelPriceList as $key=>$value){
                if($v['roomId']==$value['room_id']){
                    $value['sales_price_cny'] = sprintf('%.2f',$value['sales_price']*$exchange_rate);
                    $value['market_price_cny'] = sprintf('%.2f',$value['market_price']*$exchange_rate);
                    $hotelRoomSkuPriceList[$k]['priceList'][] = $value;
                    unset($hotelPriceList[$key]);
                }
            }
        }

        return $hotelRoomSkuPriceList;
    }

    //获取酒店产品的属性信息
    public function getHotelSkuAttrs($data)
    {
        //酒店ID
        $hotelId = $data['hotelId'];
        //获取关联的规格和属性值
        $specs = db('hotel_spu_spec_value')->where(['hotel_id'=>$hotelId,'is_deleted'=>0])->find();
        if(empty($specs['attr_json'])) return "暂未配置属性";
        $attr_json = json_decode($specs['attr_json'],true);
        return ($attr_json);
    }

    public function getChannelList()
    {
        return [
            ['value'=>'teamAmerica','name'=>'teamAmerica'],
            ['value'=>'dida','name'=>'道旅'],
        ];
    }

    public function getThirdHotelList($channel){
        switch ($channel){
            case "dida":
                return db("didahotel")->field('HotelID as id,Name as name')->select();
                break;
            case "teamAmerica":
                return db("tahotel")->field('VendorID as id,VendorName as name')->select();
                break;
            default:
                return [];
                break;
        }
    }

    public function getThirdHotelDetails($channel,$id){
        switch ($channel){
            case "dida":
                $details = db("didahotel")->field('HotelID as id,Name as name,Name_CN as en_name,Address as address,Address_CN as address,
                Longitude as lng,Latitude as lat,StarRating as star,
                "" as service_fee,"" as charging_fee,"" as breakfast_fee,CityName as show_address')->where('HotelID',$id)->find();
                break;
            case "teamAmerica":
                $details = db("tahotel")->field('VendorID as id,VendorName as name,"" as en_name,VendorAddress as address,
                Longitude as lng,Latitude as lat,HotelRating as star,
                "" as service_fee,"" as charging_fee,"" as breakfast_fee,concat(City,",",VendorAddress) as show_address')->where('VendorID',$id)->find();
                break;
            default:
                $details = [];
                break;
        }

//        if(empty($details['lng']) && empty($details['lat']) && !empty($details)){
//            if(empty($details['lng']) || empty($details['lat'])){
//                if(!empty($details['address'])){
//                    $result = (new GoogleMap())->getAddressInfo($details['address']);
//                    $result = json_decode($result,true);
//                    if(!empty($result['candidates'])){
//                        $details['lat'] = $result['candidates'][0]['geometry']['location']['lat']??'';
//                        $details['lng'] = $result['candidates'][0]['geometry']['location']['lng']??'';
//                    }
//                }
//                if(empty($details['lng']) && empty($details['lat']) && !empty($details['eng_address'])){
//                    $result = (new GoogleMap())->getAddressInfo($details['eng_address']);
//                    $result = json_decode($result,true);
//                    if(!empty($result['candidates'])){
//                        $details['lat'] = $result['candidates'][0]['geometry']['location']['lat']??'';
//                        $details['lng'] = $result['candidates'][0]['geometry']['location']['lng']??'';
//                    }
//                }
//            }
//        }
        return $details;
    }
}